using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Serialization;
using YooAsset;

namespace EGEngine
{
    public class ResourceModule : MonoBehaviour
    {
        [SerializeField] private string defaultPackageName;

        private static string _packageName;
        private static ResourcePackage _package;

        private static List<ResourceLoader> _loaders;

        public void Init()
        {
            _packageName = defaultPackageName;
            _package = YooAssets.GetPackage(_packageName);
        }

        public static ResourceLoader CreateResourceLoader()
        {
            ResourceLoader loader = null;
            foreach (var tempLoader in _loaders)
            {
                if (!tempLoader.IsUsing)
                {
                    loader = tempLoader;
                    break;
                }
            }

            if (loader == null)
            {
                loader = new ResourceLoader(_package)
                {
                    IsUsing = true
                };
                _loaders.Add(loader);
            }

            return loader;
        }

        public static async Task ReleaseUnusedResources()
        {
            await _package.UnloadUnusedAssetsAsync();
        }

        public static async Task ClearPackageUnusedCacheFiles()
        {
            await _package.ClearUnusedBundleFilesAsync();
        }

        public static async Task ClearPackageAllCacheFiles()
        {
            await _package.ClearAllBundleFilesAsync();
        }
    }
}